package org.roger.queryparse;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;

/**
 * 自定义QueryParser （禁用通配符查询和模糊查询，效率低）
 * @author luoweiyi
 */
public class CustomQueryParser extends QueryParser{

	public CustomQueryParser(String field, Analyzer analyzer) {
		super(field, analyzer);
	}

	/**
	 * 去掉通配符查询
	 */
	@Override
	protected Query getWildcardQuery(String field,
			String termStr) throws ParseException {
		throw new ParseException("Wildcard query not allowed!!!");
	}

	/**
	 * 去掉模糊查询
	 */
	@Override
	protected Query getFuzzyQuery(String field,
			String termStr, float minSimilarity) throws ParseException {
		throw new ParseException("Fuzzy query not allowed!!!");
	}

	/**
	 * 添加数字范围查询(QueryParser自带的范围查询不可以查数字范围)
	 */
	@Override
	protected Query getRangeQuery(String field,
			String part1, String part2, boolean startInclusive,
			boolean endInclusive) throws ParseException {
		try{
			return NumericRangeQuery.newIntRange(field,Integer.valueOf(part1),Integer.valueOf(part2),startInclusive,endInclusive);
		}catch(Exception e){
		}
		
		try{
			return NumericRangeQuery.newLongRange(field,Long.valueOf(part1),Long.valueOf(part2),startInclusive,endInclusive);
		}catch(Exception e){
		}
		
		try{
			return NumericRangeQuery.newFloatRange(field,Float.valueOf(part1),Float.valueOf(part2),startInclusive,endInclusive);
		}catch(Exception e){
		}
		
		try{
			return NumericRangeQuery.newDoubleRange(field,Double.valueOf(part1),Double.valueOf(part2),startInclusive,endInclusive);
		}catch(Exception e){
		}
		
		return super.getRangeQuery(field, part1, part2, startInclusive, endInclusive);
	}
}
